<template>
  <contentModel
    v-if="editModelShow"
    title="按物料添加"
    :has-footer="true"
    @close="handleClose"
  >
    <a-layout style="height: 100%" :class="screenClass">
      <a-layout>
        <a-layout-sider width="30%">
          <query-form
            :render-config="formRenderConfig"
            :render-keys="formRenderKeysByCategoryName"
            @search="searchHandle1"
            @reset="resetHandle1"
          />
          <table-container
            v-model:columns="cateColumns"
            :loading="false"
            width="center"
          >
            <a-table
              v-model:selectedKeys="selectData"
              class="table"
              :columns="cateColumns"
              :data="cateDatalist"
              :row-selection="rowSelection"
              row-key="id"
              show-empty-tree
              style="height: 60vh; margin-top: 20px"
              :pagination="false"
              @select="selectItem"
            >
              <template #secretLevel="{ record }">
                <secretLevelInfo
                  :record="{
                    secretLevel: record.secretLevel,
                    secretLevelName: record.secretLevelName,
                  }"
                />
              </template>
            </a-table>
          </table-container>
        </a-layout-sider>
        <a-layout-content style="margin: 0 16px">
          <query-page
            ref="queryFormRef"
            v-model:selectedKeys="attrSelectedKeys"
            :form-component-config="formComponentConfig"
            :form-render-config="formRenderConfig"
            :form-render-keys="formRenderKeysByMaterial"
            :table-component-config="tableComponentConfig"
            :table-render-config="tableRenderConfig"
            :table-render-keys="tableRenderKeysMaterialNameAdd"
            :data="attributeDatalist"
            row-key="id"
            height="calc(100vh - 350px)"
            :total="total"
            :loading="isLoading"
            row-selection-type="checkbox"
            @selection-change="handleSelectionChange"
          >
            <!-- :total="total"
              @query-data="getData" -->
          </query-page>
        </a-layout-content>
        <a-layout-sider width="20%"
          ><a-list size="medium">
            <template #header> 已选物料 </template>
            <a-list-item v-for="(item, index) in selectAttrList" :key="index">
              <a-row>
                <a-col :span="4">
                  <secretLevelInfo
                    :record="{
                      secretLevel: item.secretLevel,
                      secretLevelName: item.secretLevelName,
                    }"
                  />
                </a-col>
                <a-col :span="19">
                  {{ item.materialName }}
                </a-col>
                <a-col :span="1">
                  <div
                    style="float: right; cursor: pointer"
                    @click="deleteItem(item, index)"
                  >
                    x
                  </div>
                </a-col>
              </a-row>
            </a-list-item>
          </a-list></a-layout-sider
        >
      </a-layout>
    </a-layout>
    <template #footer>
      <a-button @click="handleClose">取消</a-button>
      <a-button type="primary" @click="handleSubmit">保存</a-button>
    </template>
  </contentModel>
</template>

<script setup lang="ts">
  import {
    formRenderConfig,
    formComponentConfig,
    formRenderKeysByMaterial,
    formRenderKeysByCategoryName,
  } from '@/views/basic-configuration/personnel-matrial/personnelmatrialformlist';
  import {
    tableRenderKeysMaterialNameAdd,
    tableComponentConfig,
    tableRenderConfig,
  } from '@/views/basic-configuration/personnel-matrial/procurementquery-tab';
  import queryPage from '@/common/components/query-page/index.vue';
  import { defineAsyncComponent, onMounted, reactive, ref } from 'vue';
  import queryForm from '@/common/components/query-form/index.vue';
  import secretLevelInfo from '@/common/components/secret-level-info/index.vue';
  import tableContainer from '@/common/components/table-container/index.vue';
  import useFullScreen from '@/common/hooks/fullScreen';
  import { queryAPIRecordListByPage } from '@/api/Basimanagementapi/categorymanagement';
  import {
    getAttributeQueryPage,
    saveByMaterial,
  } from '@/api/Basimanagementapi/personnel-matrial';
  import { Message } from '@arco-design/web-vue';

  const selectData = ref([]);
  const contentModel = defineAsyncComponent(
    () => import('@/common/components/content-model/index.vue')
  );
  const rowSelection = reactive({
    type: 'radio',
  });
  const attrSelectedKeys = ref([]);

  const cateColumns = ref([
    {
      title: '品类名称',
      dataIndex: 'categoryName',
      width: 150,
    },
    {
      title: '密级',
      dataIndex: 'secretLevel',
      slotName: 'secretLevel',
      width: 80,
    },
    {
      title: '采购件分类',
      dataIndex: 'procurementClassificationName',
      width: 120,
    },
    {
      title: '品类编码',
      dataIndex: 'categoryCode',
      width: 130,
      ellipsis: true,
      tooltip: true,
    },
    {
      title: '采购品类层级',
      dataIndex: 'categoryHierarchy',
      width: 120,
    },
  ]);
  const deleteItem = (val, index) => {
    selectAttrList.value.splice(index, 1);
    const itemIndex = attrSelectedKeys.value.findIndex((v) => v === val.id);
    attrSelectedKeys.value.splice(itemIndex, 1);
  };
  const cateDatalist = ref();
  const attributeDatalist = ref();
  const selectAttrList = ref([]);
  const selectId = ref();
  const getQuickAccessList = async (params: any) => {
    const { data } = await queryAPIRecordListByPage(params);
    const arr = category(data);
    cateDatalist.value = arr;
  };
  const category = (arr) => {
    arr.forEach((v) => {
      if (v.categoryHierarchy !== '三级') {
        v.disabled = true;
      }
      if (v.children !== null) {
        category(v.children);
      }
    });
    return arr;
  };
  const total = ref(0);
  const queryFormRef = ref();
  const getAttributeList = async (queryInfo: object) => {
    const params = {
      categoryLv3Id: selectId.value[0],
      ...queryInfo,
    };
    const { data } = await getAttributeQueryPage(params);
    attributeDatalist.value = data.list;
    total.value = data.total;
  };
  onMounted(() => {
    getQuickAccessList();
  });
  const selectItem = (item: any) => {
    selectId.value = item;
    getAttributeList(queryFormRef.value.getStatus());
  };
  const handleSelectionChange = (itemList: any) => {
    selectAttrList.value = itemList.map((item) => {
      if (attributeDatalist.value.find((i) => i.id === item)) {
        return attributeDatalist.value.find((i) => i.id === item);
      }
      return selectAttrList.value.find((i) => i.id === item);
    });
  };
  const isLoading = ref(false);
  const props = defineProps(['selectPersonalObj']);
  const handleSubmit = async () => {
    if (selectAttrList.value.length === 0) {
      Message.warning('请至少选择一条物料进行操作');
      return;
    }
    const params = [];
    selectAttrList.value.forEach((v) => {
      console.log(props.selectPersonalObj);
      const obj = {
        secretLevel: v.secretLevel,
        secretLevelName: v.secretLevelName,
        userId: props.selectPersonalObj.id,
        materialId: v.id,
        categoryLv1Id: v.categoryLv1Id,
        categoryLv2Id: v.categoryLv2Id,
        categoryLv3Id: v.categoryLv3Id,
        supplierId: v.supplierId,
        userCode: props.selectPersonalObj.userCode,
        userName: props.selectPersonalObj.username,
        materialCode: v.materialCode,
        materialName: v.materialName,
      };
      params.push(obj);
    });

    const { data } = await saveByMaterial(params);
    if (data) {
      Message.success('新增成功');
      handleClose();
    }
    console.log(data);
  };
  const { screenClass } = useFullScreen();

  const searchHandle1 = (data: any) => {
    console.log(data, '==========data');
    getQuickAccessList(data);
  };
  const resetHandle1 = () => {
    getQuickAccessList();
  };
  const emit = defineEmits(['close']);
  const editModelShow = ref(true);

  const handleClose = () => {
    emit('close');
  };
</script>

<style lang="less" scoped>
  .onebox {
    // border: 1px solid #000;
    display: flex;
    width: 100%;
  }

  .leftbox {
    width: 400px;
    // border: 1px solid #000;
    // float: left;
  }

  .contentbox {
    width: 900px;
    // border: 1px solid #000;
  }

  .rightbox {
    width: 500px;
    // border: 1px solid #000;
  }

  .spanitem {
    width: 40px;
    height: 18px;
    color: #fff;
    font-size: 10px;
    font-style: normal;
    text-align: center;
    text-transform: none;
    background: #d40000;
    border-radius: 503px;
  }

  .table /deep/.arco-table-container .arco-table-content-scroll-x {
    overflow-y: auto;
  }
</style>
